﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.ViewService;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text.RegularExpressions;
using System.Windows.Browser;
using System.Windows.Media.Imaging;
using SalaryChannel.SCUserService;

namespace SalaryChannel
{
    public partial class ChannelView : UserControl
    {

       //static  ViewService.ChannelViewServiceClient ServiceInstance.ViewService = ServiceInstance.ViewService;
        public ChannelView()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(ChannelView_Loaded);
            
        }

        void ChannelView_Loaded(object sender, RoutedEventArgs e)
        {
            

            ServiceInstance.ViewService.GetRegionCompleted += (s, ex) =>
                {
                    if (ex.Result == null)
                    {
                        App.MessageBox.ShowDialog(Properties.Resource.QueryCountyFailed, Title.Error);

                    }
                    else
                    {
                        this.CountyCBox.ItemsSource = ex.Result;
                        this.CountyCBox.SelectedIndex = 0;
                    }
                    IsReady = true;
                };

            ServiceInstance.ViewService.GetChannelListCompleted += new EventHandler<GetChannelListCompletedEventArgs>(Service_GetChannelListCompleted);

            ServiceInstance.ViewService.GetChannelAccountCompleted += new EventHandler<GetChannelAccountCompletedEventArgs>(Service_GetChannelAccountCompleted);
            ServiceInstance.ViewService.UpdateChannelAccountCompleted += new EventHandler<UpdateChannelAccountCompletedEventArgs>(Service_UpdateChannelAccountCompleted);
            ServiceInstance.ViewService.GetSurveyListCompleted += new EventHandler<GetSurveyListCompletedEventArgs>(Service_GetSurveyListCompleted);
            ServiceInstance.ViewService.GetSurveyDetailByIDCompleted += new EventHandler<GetSurveyDetailByIDCompletedEventArgs>(Service_GetSurveyDetailByIDCompleted);
            ServiceInstance.ViewService.InsertSurveyDetailCompleted += new EventHandler<InsertSurveyDetailCompletedEventArgs>(Service_InsertSurveyDetailCompleted);
            ServiceInstance.ViewService.GetChannelLostUsersCompleted += new EventHandler<GetChannelLostUsersCompletedEventArgs>(Service_GetChannelLostUsersCompleted);
            ServiceInstance.ViewService.GetChannelUserFeeLevelCompleted += new EventHandler<GetChannelUserFeeLevelCompletedEventArgs>(Service_GetChannelUserFeeLevelCompleted);
            ServiceInstance.ViewService.GetChannelNewUsersCompleted += new EventHandler<GetChannelNewUsersCompletedEventArgs>(Service_GetChannelNewUsersCompleted);

            ServiceInstance.ViewService.GetAlbumsByChannelIDCompleted += new EventHandler<GetAlbumsByChannelIDCompletedEventArgs>(ViewService_GetAlbumsByChannelIDCompleted);

            editAlbum.CompletedEvent += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(editAlbum_CompletedEvent);

            ServiceInstance.ViewService.DeleteAlbumCompleted += new EventHandler<DeleteAlbumCompletedEventArgs>(ViewService_DeleteAlbumCompleted);

            uploadPhoto.CompletedEvent += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(uploadPhoto_CompletedEvent);

          
            synchronousTransferPager = new SynchronousTransferPager(maxLength);

            // Slide list from animation of scrolling
            this.scrollEngine = new ScrollEngine(navigateScroller, dataList, true);
            this.scrollEngine.PanelWidth = 420.0;
            this.scrollEngine.ScrollSpeed = 15.0;

            synchronousTransferPager.SelectData += new SelectDataHandler(GetPhotoPath);

            ServiceInstance.ViewService.GetPhotoPathCompleted += new EventHandler<GetPhotoPathCompletedEventArgs>(ViewService_GetPhotoPathCompleted);
            ServiceInstance.ViewService.GetPhotoInforCompleted += new EventHandler<GetPhotoInforCompletedEventArgs>(ViewService_GetPhotoInforCompleted);

            ServiceInstance.ViewService.DeletePhotoCompleted += new EventHandler<DeletePhotoCompletedEventArgs>(ViewService_DeletePhotoCompleted);

           // this.MouseLeftButtonDown += new MouseButtonEventHandler(ChannelView_MouseLeftButtonDown);
            this.updatePhotoDialog.CompletedEvent += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(updatePhotoDialog_CompletedEvent);

            ServiceInstance.ViewService.AttachSurveyContentCompleted += new EventHandler<AttachSurveyContentCompletedEventArgs>(ViewService_AttachSurveyContentCompleted);
        }

        

       

        /// <summary>
        /// 页面初始化
        /// </summary>
        public void Initialize()
        {
            BigTab.SelectedIndex = 0;
            SelectedChannelID = string.Empty;
            SelectedChannel.Text = string.Empty;
            ChannelGrid.ItemsSource = null;

           
           
            if (this.CountyCBox.ItemsSource == null)
            {
                ServiceInstance.ViewService.GetRegionAsync(App.CurrentUser.CityCode);
                IsReady = false;
            }
            else
            {
                IsReady = true;
            }


        }
        
        #region 全局控制
        bool _isReady = true;
        /// <summary>
        /// 异步控制，当调用异步函数设为false,异步函数结束后设为true;
        /// </summary>
        bool IsReady
        {
            get
            {
                return _isReady;

            }
            set
            {
                _isReady = value;
                this.Cursor = value ? Cursors.Arrow : Cursors.Wait;
            }
        }


        /// <summary>
        ///   根据选择的页面初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!IsReady)
            {
                return;
            }

            TabControl tab = (sender as TabControl);
            if (tab.SelectedIndex != 0
                && SelectedChannelID == string.Empty)
            {
                App.MessageBox.ShowDialog(Properties.Resource.SelectChannelWarning, Title.Warning);
                tab.SelectedIndex = 0;
                IsReady = true;
                return;
            }

            if (tab.SelectedIndex == 0)
            {

                return;
            }
            else if (tab.SelectedIndex == 1)
            {//渠道信息
                ChannelInforPageInit();
            }
            else if (tab.SelectedIndex == 2)
            {//渠道风采
                ChannelViewPageInit();
                return;
            }
            else if (tab.SelectedIndex == 3)
            {//业务统计
                ChannelBusiPageInit();
            }
            else if (tab.SelectedIndex == 4)
            {//调研记录
                ChannelSurveyPageInit();

            }
        }

     
      

     
        private string _SelectedChannelID = string.Empty;
        /// <summary>
        /// 记录当前选择的渠道ID
        /// </summary>
        private string SelectedChannelID
        {
            set
            {
                if (_SelectedChannelID != value)
                {
                    _SelectedChannelID = value;
                    IsChannelBusiPageInited = false;
                    IsChannelInforPageInited = false;
                    IsChannelSurveyPageInited = false;
                    IsChannelViewPageInited = false;
                }

            }
            get
            {
                return _SelectedChannelID;
            }
        }
        #endregion

        #region 渠道在线

        /// <summary>
        /// 选择我的渠道为当前渠道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MyChannelBtn_Click(object sender, RoutedEventArgs e)
        {

            SelectedChannelID = App.CurrentUser.ChannelID;
            SelectedCountyCode = App.CurrentUser.CountyCode;
            this.SelectedChannel.Text = string.Format("{2}[{0}]{1}", App.CurrentUser.ChannelID,
               App.CurrentUser.ChannelName, Properties.Resource.ChannelSelected);
        }

        private string SelectedCountyCode = string.Empty;
        /// <summary>
        /// 根据关键字查询渠道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!IsReady)
            {
                return;
            }

            if (this.CountyCBox.SelectedItem == null)
            {
                App.MessageBox.ShowDialog(Properties.Resource.SelectCountyWarning, Title.Warning);

                return;
            }
            SelectedCountyCode = idRegex.Match(this.CountyCBox.SelectedItem.ToString()).Result("${ID}");
            try
            {
                ServiceInstance.ViewService.GetChannelListAsync(SelectedCountyCode, this.ChannelIDTB.Text, this.ChannelNameTB.Text);
            }
            catch
            {
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
                return;
            }

            IsReady = false;

        }
        /// <summary>
        /// 查询渠道完毕，显示列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_GetChannelListCompleted(object sender, GetChannelListCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
                    return;
                }
                this.ChannelGrid.ItemsSource = e.Result;
            }
            catch 
            {

                App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
            }
            finally
            {
                IsReady = true;
            }
        }

        /// <summary>
        /// 选择渠道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChannelGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ChannelGrid.SelectedItem != null)
            {
                CM_Channel c = (ChannelGrid.SelectedItem as CM_Channel);
                this.SelectedChannelID = c.ChannelID;
                 
                this.SelectedChannel.Text = string.Format("{2}[{0}]{1}", c.ChannelID, c.ChannelName,
                    Properties.Resource.ChannelSelected);
            }
            else
            {
                SelectedChannelID = string.Empty;
            }
        }

        #endregion

        #region 渠道信息

        bool IsChannelInforPageInited = false;
        /// <summary>
        /// 初始化渠道信息页
        /// </summary>
        void ChannelInforPageInit()
        {
            if (!IsChannelInforPageInited)
            {
                IsChannelInforPageInited = true;
                ServiceInstance.ViewService.GetChannelAccountAsync(SelectedChannelID);
                IsChannelInforReadOnly = true;
                inforLoading.Show();
                UserInfoEntity user = App.CurrentUser;

                //只有渠道自己和渠道管理员可以修改信息
                if (App.IsAuth(13))
                {
                    UpdateChannelInfoBtn.Visibility = Visibility.Visible;
                }
                else if (App.IsAuth(12)
                    && user.CountyCode == SelectedCountyCode)
                {
                    UpdateChannelInfoBtn.Visibility = Visibility.Visible;
                }
                else if (user.ChannelID == SelectedChannelID)
                {
                    UpdateChannelInfoBtn.Visibility = Visibility.Visible;
                }
                else
                {
                    UpdateChannelInfoBtn.Visibility = Visibility.Collapsed;
                }
            }
        }



        bool _isChannelInforReadOnly = true;
        /// <summary>
        /// 设置渠道页面是否可写
        /// </summary>
        bool IsChannelInforReadOnly
        {
            set
            {
                if (value != _isChannelInforReadOnly)
                {
                    _isChannelInforReadOnly = value;
                    ChannelInforTB.IsReadOnly = value;
                    ChiefTB.IsReadOnly = value;
                    TelTB.IsReadOnly = value;
                    AddressTB.IsReadOnly = value;
                    EmployeeTB.IsReadOnly = value;

                    PCTB.IsReadOnly = value;
                    BankTB.IsReadOnly = value;
                    BankAccountTB.IsReadOnly = value;
                    BankAccountNameTB.IsReadOnly = value;


                    UpdateChannelInfoBtn.Content = value ? Properties.Resource.Update : Properties.Resource.Submit;
                }
                
            }
            get
            {
                return _isChannelInforReadOnly;
            }
        }
        /// <summary>
        /// 更新渠道信息完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_UpdateChannelAccountCompleted(object sender, UpdateChannelAccountCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.Succeeded, Title.Information);
                    IsChannelInforReadOnly = true;
                    if (App.CurrentUser.ChannelID == SelectedChannelID)
                    {
                        App.CurrentUser.Address = AddressTB.Text;
                        App.CurrentUser.ChannelTel = TelTB.Text;
                        App.CurrentUser.Chief = ChiefTB.Text;
                        App.CurrentUser.Postcode = PCTB.Text;
                    }
                }
                else
                {
                    App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
                    IsChannelInforReadOnly = false;
                }

            }
            catch 
            {
                App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
            }
            finally
            {
                IsReady = true;
            }
        }
        /// <summary>
        /// 查询渠道信息完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_GetChannelAccountCompleted(object sender, GetChannelAccountCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.QueryChannelInfoFailed, Title.Error);
                    return;

                }

                ChannelInforTB.Text = string.IsNullOrEmpty(e.Result.Synopsis) ? Properties.Resource.ClickHereOfInfor : e.Result.Synopsis;
                ChiefTB.Text = string.IsNullOrEmpty(e.Result.Chief) ? string.Empty : e.Result.Chief;
                TelTB.Text = string.IsNullOrEmpty(e.Result.Tel) ? string.Empty : e.Result.Tel;
                AddressTB.Text = string.IsNullOrEmpty(e.Result.Address) ? string.Empty : e.Result.Address;
                EmployeeTB.Text = string.IsNullOrEmpty(e.Result.EmployeeList) ? string.Empty : e.Result.EmployeeList;

                BankTB.Text = string.IsNullOrEmpty(e.Result.Bank) ? string.Empty : e.Result.Bank;
                BankAccountNameTB.Text = string.IsNullOrEmpty(e.Result.Bank_Account_Name) ? string.Empty : e.Result.Bank_Account_Name;
                BankAccountTB.Text = string.IsNullOrEmpty(e.Result.Bank_Account) ? string.Empty : e.Result.Bank_Account;
                PCTB.Text = string.IsNullOrEmpty(e.Result.Postcode) ? string.Empty : e.Result.Postcode;

                IsChannelInforReadOnly = true;
                
            }
            catch 
            {
                App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
            }
            finally
            {
                IsReady = true;
                inforLoading.Stop();
            }
        }

        static Regex idRegex = new Regex(@"^\[(?<ID>\d+)\].*$");

        /// <summary>
        /// 更新渠道基本信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateChannelInfoBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!IsReady)
            {
                return;
            }

            if (UpdateChannelInfoBtn.Content.ToString() == Properties.Resource.Update)
            {
                IsChannelInforReadOnly = false;

            }
            else
            {
                try
                {
                    ServiceInstance.ViewService.UpdateChannelAccountAsync(
                               SelectedChannelID,
                               this.ChannelInforTB.Text == Properties.Resource.ClickHereOfInfor ? string.Empty : this.ChannelInforTB.Text,
                               this.ChiefTB.Text,
                               this.EmployeeTB.Text,
                               this.TelTB.Text,
                               this.AddressTB.Text,
                               this.PCTB.Text,
                               this.BankTB.Text,
                               this.BankAccountNameTB.Text,
                               this.BankAccountTB.Text);
                }
                catch (Exception)
                {

                    App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
                    return;
                }
                IsChannelInforReadOnly = true;
                IsReady = false;
            }
        }

        /// <summary>
        /// 当渠道简介为默认字符串时，删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChannelInforTB_GotFocus(object sender, RoutedEventArgs e)
        {
            if (!IsChannelInforReadOnly &&
                this.ChannelInforTB.Text == Properties.Resource.ClickHereOfInfor)
            {
                this.ChannelInforTB.Text = string.Empty;
            }
        }


        #endregion

        #region 渠道风采

        bool IsChannelViewPageInited = false;
        /// <summary>
        /// 初始化渠道风采页面
        /// </summary>
        void ChannelViewPageInit()
        {
            if (!IsChannelViewPageInited)
            {
                IsChannelViewPageInited = true;

                this.albumList.ItemsSource = null;
                this.dataList.ItemsSource = null;
                this.albumNewImage.Visibility = App.CurrentUser.ChannelID == _SelectedChannelID ? Visibility.Visible : Visibility.Collapsed;
                this.albumEditImage.Visibility = this.albumNewImage.Visibility;
                this.albumDelImage.Visibility = this.albumNewImage.Visibility;
                this.photoNewImage.Visibility = this.albumNewImage.Visibility;
                this.photoEditImage.Visibility = this.albumNewImage.Visibility;
                this.photoDelImage.Visibility = this.albumNewImage.Visibility;
                fullView.Source = null;
                PhotoSelected = null;
                PhotoSelectedInfor = null;
                photoComment.Clear();
                photoInfo.Clear();


                ServiceInstance.ViewService.GetAlbumsByChannelIDAsync(SelectedChannelID);

                albumLoading.Show();
                IsReady = false;
            }
        }


        #region 相册操作

        /// <summary>
        /// 查询相册列表完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ViewService_GetAlbumsByChannelIDCompleted(object sender, GetAlbumsByChannelIDCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.QueryAlbumsFailed, Title.Error);
                }
                else
                {
                    this.albumList.ItemsSource = e.Result;
                    
                }
            }
            catch 
            {

                App.MessageBox.ShowDialog(Properties.Resource.QueryAlbumsFailed, Title.Error);
            }
            finally
            {
                IsReady = true;
                albumLoading.Stop();
            }

        }

        private void albumNewImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            editAlbum.ChannelID = SelectedChannelID;
            editAlbum.Operation = Usage.Insert;
            editAlbum.AlbumName = string.Empty;
            editAlbum.Description = string.Empty;
            editAlbum.HeaderTitle = "新建相册";
            editAlbum.Visibility = Visibility.Visible;

        }

        private void albumEditImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (albumList.SelectedItem != null)
            {
                VW_AlbumContains tem = (albumList.SelectedItem as VW_AlbumContains);
                editAlbum.Operation = Usage.Update;
                editAlbum.AlbumID = tem.AlbumID;
                editAlbum.AlbumName = tem.Name;
                editAlbum.HeaderTitle = "编辑相册";
                editAlbum.Description = string.IsNullOrEmpty(tem.Description) ? string.Empty: tem.Description;

                editAlbum.Visibility = Visibility.Visible;
            }
        }

    
        private void albumDelImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (albumList.SelectedItem != null)
            {

                App.MessageBox.ShowDialog(string.Format("您将删除相册[{0}]及其中的所有照片。是否继续？",
                    (albumList.SelectedItem as VW_AlbumContains).Name), new Action(DelAlbumAction), Title.Warning);
              
            }
           
        }
        void DelAlbumAction()
        {
            try
            {
                VW_AlbumContains tem = (albumList.SelectedItem as VW_AlbumContains);
                ServiceInstance.ViewService.DeleteAlbumAsync(tem.AlbumID);
                IsReady = false;
            }
            catch
            {
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
            }
        }

        void ViewService_DeleteAlbumCompleted(object sender, DeleteAlbumCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.Succeeded, Title.Information);
                    ServiceInstance.ViewService.GetAlbumsByChannelIDAsync(SelectedChannelID);

                }
                else
                {
                    IsReady = true;
                    App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);

                }
            }
            catch
            {
                IsReady = true;
                App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
            }
            
        }

        void editAlbum_CompletedEvent(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            try
            {
                ServiceInstance.ViewService.GetAlbumsByChannelIDAsync(SelectedChannelID);
                albumLoading.Show();
                IsReady = false;
            }
            catch 
            {
                albumLoading.Stop() ;
                IsReady = true;
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
            }

        }

       
        #endregion

        #region 图片滚动控制
        /// <summary>
        /// Synchronous transfer pager
        /// </summary>
        SynchronousTransferPager synchronousTransferPager;

        /// <summary>
        /// Max content of the photo slide
        /// </summary>
        private readonly int maxLength = 4;


        /// <summary>
        /// The user defined Scroller
        /// </summary>
        private ScrollEngine scrollEngine;

        private void SetNavigatorButton()
        {
            if (!synchronousTransferPager.CanPre())
            {
                previousButton.Opacity = 0.2;
                previousButton.Cursor = Cursors.Arrow;
            }
            else
            {
                previousButton.Opacity = 1;
                previousButton.Cursor = Cursors.Hand;
            }

            if (!synchronousTransferPager.CanNext())
            {
                nextButton.Opacity = 0.2;
                nextButton.Cursor = Cursors.Arrow;
            }
            else
            {
                nextButton.Opacity = 1;
                nextButton.Cursor = Cursors.Hand;
            }
        }

        void GetPhotoPath(int StartIndex, int MaxLength)
        {
            string albumID = string.Empty;
            if(albumList.SelectedItem != null)
            {
                albumID = (albumList.SelectedItem as VW_AlbumContains).AlbumID;
            }
            ServiceInstance.ViewService.GetPhotoPathAsync(SelectedChannelID,
                albumID, StartIndex, maxLength);
            slideImageLoading.Show();
            fullViewLoading.Show();
        }

        void ViewService_GetPhotoPathCompleted(object sender, GetPhotoPathCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
                    return;
                }

                FillList(e.Result);
            }
            catch 
            {

                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
            }
        }
      
        /// <summary>
        /// Fill the dataList
        /// </summary>
        /// <param name="list"></param>
        public void FillList(List<VW_PhotoPath> list)
        {
            fullViewLoading.Stop();
            slideImageLoading.Stop();

            synchronousTransferPager.GetDataCompleted(list.Count);

            SetNavigatorButton();

            if (list.Count != 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].Path = (new Uri(HtmlPage.Document.DocumentUri, new Uri(list[i].Path, UriKind.Relative))).ToString();
                }

                // If the initial page is shown firstly, there is not animation
                // Else, there is a scrolling animation
                if (synchronousTransferPager.IsInitialPage())
                {
                    dataList.ItemsSource = list;
                    dataList.SelectedIndex = 0;
                }
                else
                {
                    scrollEngine.ScrollToHorizontal(synchronousTransferPager.Direction, list);
                }
            }
            else
            {
                if (synchronousTransferPager.IsEmpty())
                {
                    //VW_PhotoPath photo = new VW_PhotoPath();
                    //photo.Path = (new Uri(HtmlPage.Document.DocumentUri, new Uri(@"Image/empty.jpg", UriKind.Relative))).ToString();
                    //list.Add(photo);

                    dataList.ItemsSource = null;
                    fullView.Source = null;
                    PhotoSelected = null;
                    PhotoSelectedInfor = null;
                    photoComment.Clear();
                    photoInfo.Clear();
                }
            }
        }
        /// <summary>
        /// 选择相册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void albumList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.albumList.SelectedIndex < 0)
            {
                if (!IsShowAll)
                {
                    return;
                }
                else
                {
                    IsShowAll = false;
                }
            }
           
            synchronousTransferPager.BindData();
        }
        private bool IsShowAll = false;
        /// <summary>
        /// 显示该渠道的所有图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowAllBtn_Click(object sender, RoutedEventArgs e)
        {
            IsShowAll = true;
            this.albumList.SelectedIndex = -1;
            
        }
      
        /// <summary>
        /// 向左流动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrevious_Click(object sender, RoutedEventArgs e)
        {

            lock (scrollEngine)
            {
                if (scrollEngine.Ready)
                {
                    synchronousTransferPager.GetData(Direction.Previous);
                }
            }
        }

        /// <summary>
        /// 向右滚动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            lock (scrollEngine)
            {
                if (scrollEngine.Ready)
                {
                    synchronousTransferPager.GetData(Direction.Next);
                }
            }
        }

        private VW_PhotoPath PhotoSelected=null;


       
        /// <summary>
        /// 点击滚动列表的小图，显示大图及图片信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {                  
            if (!IsReady)
            {
                return;
            }
            if (dataList.SelectedItem != null)
            {
                try
                {
                    PhotoSelected = dataList.SelectedItem as VW_PhotoPath;
                    this.fullView.Source = new BitmapImage(new Uri(PhotoSelected.Path));
                }
                catch 
                {
                    PhotoSelected = null;
                    PhotoSelectedInfor = null;
                    return;
                }
                try
                {
                    ServiceInstance.ViewService.GetPhotoInforAsync(PhotoSelected.PhotoID);
                    photoComment.BindData(PhotoSelected.PhotoID);
                    IsReady = false;
                }
                catch
                {
                    PhotoSelectedInfor = null;
                    App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
                }

            }
            else
            {
                photoInfo.Clear();
            }
        }
        private VW_PhotoInfor PhotoSelectedInfor = null;
        void ViewService_GetPhotoInforCompleted(object sender, GetPhotoInforCompletedEventArgs e)
        {
            try
            {
                PhotoSelectedInfor = e.Result;
                photoInfo.BindData(e.Result);
            }
            catch
            {
                PhotoSelectedInfor = null;
                App.MessageBox.ShowDialog("获取照片信息失败",
                    Title.Error);
            }
            finally
            {
                IsReady = true;
            }
        }
        #endregion


        #region 照片信息和评论页面动画
        private bool IsPhotoInfoOut = false;
        private void photoInfo_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!IsPhotoInfoOut)
            {
                photoInfoOutStoryBoard.Begin();
                IsPhotoInfoOut = true;
                photoInfo.SetValue(Canvas.ZIndexProperty, photoInforAndCmtZIndex + ZindexStep);
            }
        }

        private void photoInfo_MouseLeave(object sender, MouseEventArgs e)
        {
            if (IsPhotoInfoOut)
            {
                photoInfoInStoryBoard.Begin();
                IsPhotoInfoOut = false;
                photoInfo.SetValue(Canvas.ZIndexProperty, photoInforAndCmtZIndex );
            }

        }

        private bool IsPhotoComOut = false;
        private void photoComment_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!IsPhotoComOut)
            {
                photoCommentOutStoryBoard.Begin();
                IsPhotoComOut = true;
                photoComment.SetValue(Canvas.ZIndexProperty, photoInforAndCmtZIndex+ZindexStep);
            }
        }

        private void photoComment_MouseLeave(object sender, MouseEventArgs e)
        {
            if (IsPhotoComOut)
            {
                photoCommentInStoryBoard.Begin();
                IsPhotoComOut = false;
                photoComment.SetValue(Canvas.ZIndexProperty, photoInforAndCmtZIndex );
            }

        }

        readonly int photoInforAndCmtZIndex = 99;
        readonly int ZindexStep = 10;

        #endregion

       
        #region 照片上传和更新操作

        private void photoNewImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            uploadPhoto.Initialize(SelectedChannelID, albumList.ItemsSource as List<VW_AlbumContains>);
            
        }


        void uploadPhoto_CompletedEvent(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            try
            {
                IsReady = false;

                ServiceInstance.ViewService.GetAlbumsByChannelIDAsync(SelectedChannelID);
            }
            catch
            {
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
            }
        }


        private void photoEditImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if ( PhotoSelectedInfor  != null)
            {

                updatePhotoDialog.BindData(PhotoSelectedInfor.PhotoID, PhotoSelectedInfor.Title,
                    PhotoSelectedInfor.Description, albumList.SelectedIndex,
                    (this.albumList.ItemsSource as List<VW_AlbumContains>));
            }
        }

        /// <summary>
        /// 更新完照片信息后重新获取。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void updatePhotoDialog_CompletedEvent(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            try
            {
                if ((bool)e.UserState)
                {//已变更相册
                    ServiceInstance.ViewService.GetAlbumsByChannelIDAsync(SelectedChannelID);
                }
                ServiceInstance.ViewService.GetPhotoInforAsync(PhotoSelected.PhotoID);
            }
            catch 
            {
                App.MessageBox.ShowDialog("获取更新后的信息失败");
            }
        }

        private void photoDelImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (PhotoSelected != null)
            {
                App.MessageBox.ShowDialog(Properties.Resource.DelWarning,
                    new Action(PhotoDeleteAction), Title.Information);
            }
        }

        void PhotoDeleteAction()
        {
            try
            {
                ServiceInstance.ViewService.DeletePhotoAsync(PhotoSelected.PhotoID);
            }
            catch 
            {
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
            }
        }
        void ViewService_DeletePhotoCompleted(object sender, DeletePhotoCompletedEventArgs e)
        {
           
            try
            {
                string msg = string.Empty;
                if (e.Result)
                {
                    msg = Properties.Resource.Succeeded;
                    ServiceInstance.ViewService.GetAlbumsByChannelIDAsync(SelectedChannelID);
                }
                else
                {
                    msg = Properties.Resource.TryAgain;
                }
                App.MessageBox.ShowDialog(msg);
            }
            catch 
            {
                App.MessageBox.ShowDialog(Properties.Resource.TryAgain);
            }
        }
       
        #endregion

        #endregion

        #region 业务统计

        bool IsChannelBusiPageInited = false;
        /// <summary>
        /// 初始化业务统计页面
        /// </summary>
        void ChannelBusiPageInit()
        {
            if (!IsChannelBusiPageInited)
            {
                IsChannelBusiPageInited = true;

                ChannelUserFeeGrid.ItemsSource = null;
                ChannelUserLostGrid.ItemsSource = null;
                ChannelNewUserGrid.ItemsSource = null;

                ServiceInstance.ViewService.GetChannelUserFeeLevelAsync(SelectedChannelID, Guid.NewGuid());
                ServiceInstance.ViewService.GetChannelNewUsersAsync(SelectedChannelID, Guid.NewGuid());
                ServiceInstance.ViewService.GetChannelLostUsersAsync(SelectedChannelID, Guid.NewGuid());
                newUserLoading.Show();
                lostUserLoading.Show();
                userFeeLoading.Show();
                ChannelBusiInitStep = 0;
                this.IsEnabled = false;
            }
        }

        private readonly int MaxChannelBusiInitStep = 3;
        private int _ChannelBusiInitStep = 0;
        /// <summary>
        /// 当三个异步过程结束时，才能完成初始化
        /// </summary>
        public int ChannelBusiInitStep
        {
            get { return _ChannelBusiInitStep; }
            set 
            {
                if (value < 0)
                {
                    return;
                }
                else if (value >= MaxChannelBusiInitStep)
                {
                    _ChannelBusiInitStep = 0;
                    this.IsEnabled = true;
                }
                else
                {
                    _ChannelBusiInitStep = value;
                }

                
            }
        }


        /// <summary>
        /// 查询渠道新增用户完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_GetChannelNewUsersCompleted(object sender, GetChannelNewUsersCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.QueryNewUsersFailed, Title.Error);
                }
                else
                {
                    this.ChannelNewUserGrid.ItemsSource = e.Result;
                    
                }
            }
            catch 
            {

                App.MessageBox.ShowDialog(Properties.Resource.QueryNewUsersFailed, Title.Error);
            }
            finally
            {
                ChannelBusiInitStep ++;
                newUserLoading.Stop();
            }
        }

        /// <summary>
        /// 查询渠道用户消费完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_GetChannelUserFeeLevelCompleted(object sender, GetChannelUserFeeLevelCompletedEventArgs e)
        {

            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.QueryUserFeeFailed, Title.Error);
                }
                else
                {
                    this.ChannelUserFeeGrid.ItemsSource = e.Result;
                    
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog(Properties.Resource.QueryUserFeeFailed, Title.Error);                
            }
            finally
            {
                ChannelBusiInitStep++;
                userFeeLoading.Stop();
            }
        }
        /// <summary>
        /// 查询渠道离网情况完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_GetChannelLostUsersCompleted(object sender, GetChannelLostUsersCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.QueryLostUsersFailed, Title.Error);

                }
                else
                {
                    this.ChannelUserLostGrid.ItemsSource = e.Result;
                    
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog(Properties.Resource.QueryLostUsersFailed, Title.Error);
            }
            finally
            {
                 ChannelBusiInitStep++;
                 lostUserLoading.Stop();
            }

        }
        #endregion

        #region 调研记录


        bool IsChannelSurveyPageInited = false;
        /// <summary>
        /// 初始化调研记录页面
        /// </summary>
        void ChannelSurveyPageInit()
        {
            if (!IsChannelSurveyPageInited)
            {
                IsChannelSurveyPageInited = true;

                this.SurveyHisGrid.ItemsSource = null;
                this.SubjectTB.Text = string.Empty;
                this.DateTB.Text = string.Empty;
                ScoreTB.Text = string.Empty;
                SurveyChiefTB.Text = string.Empty;
                EmployeeTB.Text = string.Empty;
                ContentTB.Text = string.Empty;
                AttachCancelBtn.IsEnabled = false;

                if (App.IsAuth(13))
                {
                    NewSurveyBtn.Visibility = Visibility.Visible;
                    
                }
                else if (App.IsAuth(12)
                    && App.CurrentUser.CountyCode == SelectedCountyCode
                    )
                {//县级管理员
                    NewSurveyBtn.Visibility = Visibility.Visible;
                    AttachContentBtn.IsEnabled = true;
                }
                else
                {
                    NewSurveyBtn.Visibility = Visibility.Collapsed;
                    AttachContentBtn.IsEnabled = false;
                }


                ServiceInstance.ViewService.GetSurveyListAsync(SelectedChannelID);
                surveyLoading.Show();
            }
        }

        /// <summary>
        /// 新增调研记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewSurveyBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!IsReady)
            {
                return;
            }
            if (NewSurveyBtn.Content.ToString() == Properties.Resource.New)
            {
                IsSurveyDetailReadOnly = false;

                SubjectTB.Text = string.Empty;
                DateTB.Text = string.Empty;
                ScoreTB.Text = string.Empty;
                SurveyChiefTB.Text = string.Empty;
                SurveyrTB.Text = string.Empty;
                ContentTB.Text = string.Empty;
                return;
            }
            int score = -1;

            if (!string.IsNullOrEmpty(this.ScoreTB.Text.Trim()))
            {
                try
                {
                    score = int.Parse(this.ScoreTB.Text.Trim());
                    if (score < 1 || score > 100)
                    {
                        throw new Exception();
                    }
                }
                catch
                {
                    App.MessageBox.ShowDialog(Properties.Resource.IllegalScore, Title.Warning);
                    return;
                }
            }
            DateTime sdate;

            try
            {
                sdate = DateTime.Parse(this.DateTB.Text);
            }
            catch
            {
                App.MessageBox.ShowDialog(Properties.Resource.IllagalDate, Title.Warning);
                return;
            }

            try
            {
                ServiceInstance.ViewService.InsertSurveyDetailAsync(SelectedChannelID, sdate,
                       this.SubjectTB.Text, SurveyChiefTB.Text, SurveyrTB.Text, score,
                       this.ContentTB.Text, App.CurrentUser.UserID);
            }
            catch
            {
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
            }
            IsReady = false;
            IsSurveyDetailReadOnly = true;
        }

        /// <summary>
        /// 选择一条调研记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SurveyHisGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SurveyHisGrid.SelectedItem != null)
            {
                try
                {
                    ServiceInstance.ViewService.GetSurveyDetailByIDAsync((SurveyHisGrid.SelectedItem as Survey).ID, Guid.NewGuid());
                    IsReady = false;
                }
                catch
                {

                    App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
                }
            }
        }

     
        /// <summary>
        /// 新增调研信息完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_InsertSurveyDetailCompleted(object sender, InsertSurveyDetailCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    ServiceInstance.ViewService.GetSurveyListAsync(SelectedChannelID);
                    surveyLoading.Show();
                    App.MessageBox.ShowDialog(Properties.Resource.Succeeded, Title.Information);
                }
                else
                {
                    App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
                IsSurveyDetailReadOnly = false;
                return;
            }
            finally
            {
                IsReady = true;
            }
        }
        /// <summary>
        /// 查询调研信息完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_GetSurveyDetailByIDCompleted(object sender, GetSurveyDetailByIDCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.QuerySurveyDetailFailed, Title.Error);
                    return;
                }
                SubjectTB.Text = e.Result.Subject;
                DateTB.Text = e.Result.SurveyDate.ToShortDateString();
                ScoreTB.Text = e.Result.Score.Value.ToString();
                SurveyChiefTB.Text = e.Result.SurveyChief;
                SurveyrTB.Text = e.Result.Surveyer;
                ContentTB.Text = e.Result.Content;
                IsSurveyDetailReadOnly = true;
            }
            catch 
            {

                App.MessageBox.ShowDialog(Properties.Resource.QuerySurveyDetailFailed, Title.Error); 
            }
            finally
            {
                IsReady = true;
            }
        }

        bool _IsSurveyDetailReadOnly = false;
        /// <summary>
        /// 设置调研页面是否可写
        /// </summary>
        bool IsSurveyDetailReadOnly
        {
            set
            {
                _IsSurveyDetailReadOnly = value;
                SubjectTB.IsReadOnly = value;
                DateTB.IsReadOnly = value;
                ScoreTB.IsReadOnly = value;
                SurveyChiefTB.IsReadOnly = value;
                SurveyrTB.IsReadOnly = value;
                ContentTB.IsReadOnly = value;
                NewSurveyBtn.Content = value ? Properties.Resource.New : Properties.Resource.Submit;
            }
            get
            {
                return _IsSurveyDetailReadOnly;
            }
        }

        /// <summary>
        /// 查询调研记录完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Service_GetSurveyListCompleted(object sender, GetSurveyListCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog(Properties.Resource.QuerySurveysFailed, Title.Error);
                   
                    return;
                }
                SurveyHisGrid.ItemsSource = e.Result;
            }
            catch 
            {

                App.MessageBox.ShowDialog(Properties.Resource.QuerySurveysFailed, Title.Error);

            }
            finally
            {
                IsReady = true;
                IsSurveyDetailReadOnly = true;
                surveyLoading.Stop();
            }
        }

        /// <summary>
        /// 将整改结果追加到调研结果中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AttachContentBtn_Click(object sender, RoutedEventArgs e)
        {
            if (AttachContentBtn.Content.Equals("追加"))
            {
                if (SurveyHisGrid.SelectedItem != null
                    && _IsSurveyDetailReadOnly)
                {
                    this.AttachTB.Visibility = Visibility.Visible;
                    AttachContentBtn.Content = "提交";

                    SurveyHisGrid.IsEnabled = false;
                    NewSurveyBtn.IsEnabled = false;
                    AttachCancelBtn.IsEnabled = true;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(AttachTB.Text))
                {
                    return;
                }
                SalaryChannel.SCUserService.UserInfoEntity user = App.CurrentUser;
                string attachBody = string.Format("\r\r***********************************"
                    +"\r[{0}]{1} 于{2} 追加：\r{3}", user.UserID,
                    user.UserName, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(),
                    AttachTB.Text.Trim());
                AttachContentBtn.Content = "追加";
                try
                {
                    ServiceInstance.ViewService.AttachSurveyContentAsync((SurveyHisGrid.SelectedItem as Survey).ID,
                               attachBody, attachBody);
                     AttachCancelBtn.IsEnabled =false;
                }
                catch 
                {
                    SurveyHisGrid.IsEnabled = true;
                    NewSurveyBtn.IsEnabled = true;
                    App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed);
                }
                   
            }

        }

        /// <summary>
        /// 在追加提交加取消追加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AttachCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            AttachTB.Text = string.Empty;
            AttachTB.Visibility = Visibility.Collapsed;
            SurveyHisGrid.IsEnabled = true;
            NewSurveyBtn.IsEnabled = true;
            AttachCancelBtn.IsEnabled = false;
            AttachContentBtn.Content = "追加";

        }

        void ViewService_AttachSurveyContentCompleted(object sender, AttachSurveyContentCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    ContentTB.Text += e.UserState.ToString();
                    ContentTB.SelectionStart = ContentTB.Text.Length - 1;
                   // ContentTB.Select(
                    AttachTB.Text = string.Empty;

                }
                else
                {
                    App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
                }
            }
            catch
            {
                App.MessageBox.ShowDialog(Properties.Resource.TryAgain, Title.Error);
            }
            finally
            {
                SurveyHisGrid.IsEnabled = true;
                NewSurveyBtn.IsEnabled = true;
                AttachTB.Visibility = Visibility.Collapsed;
            }
        }

        #endregion

       
       

    }
}
